package com.zzsz.utils;

import com.zzsz.domain.EmailLog;
import com.zzsz.mapper.ProductWarnMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

/**
 * --- 这有何难 ---
 * ƪ(˘⌣˘)ʃ
 *
 * @author 超级无敌张恒阳大王
 * @date 5/9/2025
 * @desc 邮件发送日志切面
 */
@Slf4j
@Aspect
@Component
public class EmailLogAspect {

	@Autowired
	private ProductWarnMapper productWarnMapper;

	// 定义切点,拦截IEmailService接口的所有方法
	@Pointcut("execution(* com.zzsz.utils.IEmailService.*(..)))")
	public void emailSendPointCut() {
	} // 用于承载切面注解,成为切点的名字

	// 环绕通知,记录邮件发送的详细信息
	@Around("emailSendPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		// 获取方法名
		String methodName = point.getSignature().getName();

		// 获取参数
		Object[] args = point.getArgs();

		// 记录开始时间
		long startTime = System.currentTimeMillis();
		// 要插入到数据库中的参数
		boolean success = true;
		String errorMsg = null;
		String from = null;
		String to = null;
		String subject = null;
		String content = null;

		log.info(" 开始发送邮件，方法: {}", methodName);

		if ("sendText".equals(methodName) && args.length >= 4) {

			from = (String) args[0];
			to = (String) args[1];
			subject = (String) args[2];
			content = (String) args[3];
			log.info("   发件人: {}, 收件人: {}, 主题: {} ,内容: {}", from, to, subject, content);
		}

		try {
			// 执行原方法
			return point.proceed();
		} catch (Exception e) {
			success = false;
			errorMsg = e.getMessage();
			log.error("邮件发送失败: {}", e.getMessage());
			throw e; // 抛出异常,不影响原有逻辑
		} finally {
			// 记录结束时间和耗时
			long endTime = System.currentTimeMillis();
			long costTime = endTime - startTime;

			// 将日志保存到数据库
			EmailLog emailLog = new EmailLog();
			emailLog.setFromEmail(from);
			emailLog.setToEmail(to);
			emailLog.setSubject(subject);
			emailLog.setContentSummary(content);
			emailLog.setSendSuccess(success);
			emailLog.setErrorMessage(errorMsg);
			emailLog.setSendTime(new Date());
			emailLog.setSendDuration(costTime);

			// 插入数据到数据库
			try {
				productWarnMapper.insert(emailLog);
				log.info("邮件日志成功保存到数据库");
			} catch (Exception e) {
				log.error("邮件日志保存失败: {}", e.getMessage());
			}

			log.info("📊 邮件发送完成，耗时: {}ms, 结果: {}", costTime, success ? "成功" : "失败");

		}

	}

}
